﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace BusinessLogicLayer
{
    public class ErrorLogger
    {
        /// <summary>
        /// 
        /// </summary>
        private static String AppErrorLogFileName = "ErrorLog.txt";
        private static String AppInfoLogFileName = "InfoLog.txt";

        /// <summary>
        /// Log error messages from the Application
        /// </summary>
        /// <param name="message"></param>
        public static void LogMessage(String pMessage)
        {
            bool Successful = false;

            for (int idx = 0; idx < 10; idx++)
            {
                try
                {
                    // Log message to default log file.
                    StreamWriter str = new StreamWriter(AppErrorLogFileName, true);
                    // Wri9te text with no buffering
                    str.AutoFlush = true;
                    str.WriteLine("#######################################");
                    str.WriteLine("Time: " + DateTime.Now.ToString() +
                    Environment.NewLine + "Message: " + pMessage);
                    str.Close();

                    Successful = true;
                }
                catch (Exception)
                {
                }

                if (Successful == true)     // Logging successful
                    break;
                else                        // Logging failed, retry in 100 milliseconds
                    Thread.Sleep(10);
            }
        }

        /// <summary>
        /// Log Exception Msg and Exception Stack
        /// </summary>
        /// <param name="pExeption">Exception</param>
        public static void LogException(Exception pExeption)
        {
            LogException(pExeption, null);
        }

        /// <summary>
        /// Log Exception Msg, Exception Stack and Custom Message
        /// </summary>
        /// <param name="pExeption">Exception</param>
        /// <param name="pMessage">Custom Message</param>
        public static void LogException(Exception pExeption, String pMessage)
        {
            String str_inner = "";

            try
            {
                str_inner = Environment.NewLine +
                "Inner Exception Msg: " + pExeption.InnerException.Message +
                "Inner Exception Stack: " + pExeption.InnerException.StackTrace;
            }
            catch (Exception)
            {
            }

            if (string.IsNullOrEmpty(pMessage))
                LogMessage("Exception: " + pExeption.Message + Environment.NewLine +
                    "Stack: " + str_inner);
            else
                LogMessage(pMessage + Environment.NewLine + "Exception: " + pExeption.Message + Environment.NewLine +
                "Stack: " + str_inner);

        }
    }
}

